"""
@File    : Request.py
@Time    : 2019/7/15 14:36
@Author  : LiuFeiYu
@Email   : liufeiyu@sunrise.net
@Software: PyCharm
@Remark  : 基于requests的二次封装
"""

import os
import random
import requests
import Common.Consts
from requests_toolbelt import MultipartEncoder
from typing import Union


class Request:

    # def __init__(self, env):
    #     """
    #     :param env:
    #     """
    #     self.session = Session.Session()
    #     self.get_session = self.session.get_session(env)

    @staticmethod
    def get_request(url: str, data: dict = None, **kwargs) -> Union[dict, str]:
        """
        Get请求
        """
        if not url.startswith('http://'):
            url = '%s%s' % ('http://', url)

        try:
            response = requests.get(url=url, params=data, **kwargs)
            response.raise_for_status()
        except Exception as e:
            return f'Request Fail , Reason : {e}'

        # time_consuming为响应时间，单位为毫秒
        time_consuming = response.elapsed.microseconds / 1000
        # time_total为响应时间，单位为秒
        time_total = response.elapsed.total_seconds()

        Common.Consts.API_RESPONSE_TIME_LIST.append(time_consuming)

        response_dicts = dict()
        # 响应内容的相应码
        response_dicts['code'] = response.status_code

        try:
            response_dicts['body'] = response.json()
        except Exception as e:
            response_dicts['body'] = ''
            return f'Response to dicts Fail , Reason : {e}'

        # 响应内容
        response_dicts['text'] = response.text
        # 响应时间
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total

        return response_dicts

    @staticmethod
    def post_request(url: str, data: dict = None, json: dict = None, **kwargs) -> Union[dict, str]:
        """
        Post请求
        """
        if not url.startswith('http://'):
            url = '%s%s' % ('http://', url)
            print(url)
        try:
            response = requests.post(url, data=data, json=json, **kwargs)
            response.raise_for_status()

        except Exception as e:
            return f'Request Fail , Reason : {e}'

        # time_consuming为响应时间，单位为毫秒
        time_consuming = response.elapsed.microseconds / 1000
        # time_total为响应时间，单位为秒
        time_total = response.elapsed.total_seconds()

        Common.Consts.API_RESPONSE_TIME_LIST.append(time_consuming)

        response_dicts = dict()
        response_dicts['code'] = response.status_code
        try:
            response_dicts['body'] = response.json()
        except Exception as e:
            response_dicts['body'] = ''
            return f'Response to dicts Fail , Reason : {e}'

        response_dicts['text'] = response.text
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total

        return response_dicts

    @staticmethod
    def post_request_multipart(url, data, header, file_parm, file, f_type) -> Union[dict, str]:
        """
        提交Multipart/form-data 格式的Post请求
        """
        if not url.startswith('http://'):
            url = '%s%s' % ('http://', url)
            print(url)
        try:
            data[file_parm] = os.path.basename(file), open(file, 'rb'), f_type

            enc = MultipartEncoder(
                fields=data,
                boundary='--------------' + str(random.randint(1e28, 1e29 - 1))
            )

            header['Content-Type'] = enc.content_type
            response = requests.post(url=url, params=data, headers=header)
            response.raise_for_status()
        except Exception as e:
            return f'Request Fail , Reason : {e}'

        # time_consuming为响应时间，单位为毫秒
        time_consuming = response.elapsed.microseconds / 1000
        # time_total为响应时间，单位为秒
        time_total = response.elapsed.total_seconds()

        Common.Consts.API_RESPONSE_TIME_LIST.append(time_consuming)

        response_dicts = dict()
        response_dicts['code'] = response.status_code
        try:
            response_dicts['body'] = response.json()
        except Exception as e:
            response_dicts['body'] = ''
            return f'Response to dicts Fail , Reason : {e}'

        response_dicts['text'] = response.text
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total

        return response_dicts

    @staticmethod
    def put_request(url: str, data: dict = None, json: dict = None, **kwargs) -> Union[dict, str]:
        """
        Put请求
        :return:

        """
        if not url.startswith('http://'):
            url = '%s%s' % ('http://', url)

        try:
            response = requests.put(url, data=data, json=json, **kwargs)
            response.raise_for_status()
        except Exception as e:

            return f'Request Fail , Reason : {e}'

        time_consuming = response.elapsed.microseconds / 1000
        time_total = response.elapsed.total_seconds()

        Common.Consts.API_RESPONSE_TIME_LIST.append(time_consuming)

        response_dicts = dict()
        response_dicts['code'] = response.status_code

        try:
            response_dicts['body'] = response.json()

        except Exception as e:
            response_dicts['body'] = ''
            return f'Response to dicts Fail , Reason : {e}'

        response_dicts['text'] = response.text
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total

        return response_dicts

    @staticmethod
    def delete_request(url: str, data: dict = None, json: dict = None, **kwargs) -> Union[dict, str]:
        """
        Delete请求
        :return:

        """
        if not url.startswith('http://'):
            url = '%s%s' % ('http://', url)

        try:
            response = requests.delete(url, data=data, json=json, **kwargs)
            response.raise_for_status()
        except Exception as e:

            return f'Request Fail , Reason : {e}'

        time_consuming = response.elapsed.microseconds / 1000
        time_total = response.elapsed.total_seconds()

        Common.Consts.API_RESPONSE_TIME_LIST.append(time_consuming)

        response_dicts = dict()
        response_dicts['code'] = response.status_code

        try:
            response_dicts['body'] = response.json()

        except Exception as e:
            response_dicts['body'] = ''
            return f'Response to dicts Fail , Reason : {e}'

        response_dicts['text'] = response.text
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total

        return response_dicts

    @staticmethod
    def response_error_num(state: bool):
        """
        全局变量-接口错误数量
        :param state: 每次接口是否错误参照标准
        :return:
        """
        if state:
            pass
        else:
            Common.Consts.API_RESPONSE_NUMBER += 1

    @staticmethod
    def save_error_api_data(pro_id, summary, description, assignee):
        """
        储存接口错误信息
        :param pro_id:项目id
        :param summary:主题
        :param description:描述
        :param assignee:报告人
        :return:
        """
        error_data = {
            "project_id": pro_id,
            "summary": summary,
            "description": description,
            "assignee": assignee
        }

        Common.Consts.API_ERROR_RESPONSE_DATA.append(error_data)


if __name__ == '__main__':
    # a = Request()
    # url = 'http://192.168.10.237/login/login/entry'
    # data = {
    #     "loginName": "admin",
    #     "password": "admin",
    #     "type": "0"
    # }
    # res = a.post_request(url, json=data)
    # print(res)
    pass
